package com.mars.base.common.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.HttpClient;

public class IpHelper {

	private static final Logger logger = LoggerFactory.getLogger(IpHelper.class) ;

	private static String LOCAL_IP_STAR_STR = "192.168.";

	static {
		String ip = null;
		String hostName = null;
		try {
			hostName = InetAddress.getLocalHost().getHostName();
			InetAddress[] ipAddr = InetAddress.getAllByName(hostName);
			for (int i = 0; i < ipAddr.length; i++) {
				ip = ipAddr[i].getHostAddress();
				if (ip.startsWith(LOCAL_IP_STAR_STR)) {
					break;
				}
			}
			if (ip == null) {
				ip = ipAddr[0].getHostAddress();
			}

		} catch (UnknownHostException e) {
			logger.error("IpHelper error.");
			e.printStackTrace();
		}

		LOCAL_IP = ip;
		HOST_NAME = hostName;

	}

	/** 系统的本地IP地址 */
	public static final String LOCAL_IP;

	/** 系统的本地服务器名 */
	public static final String HOST_NAME;

	/**
	 * <p>
	 *  获取客户端的IP地址的方法是：request.getRemoteAddr()，这种方法在大部分情况下都是有效的。
	 *  但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了，如果通过了多级反向代理的话，
	 *  X-Forwarded-For的值并不止一个，而是一串IP值， 究竟哪个才是真正的用户端的真实IP呢？
	 *  答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
	 *  例如：X-Forwarded-For：192.168.1.110, 192.168.1.120,
	 *  192.168.1.130, 192.168.1.100 用户真实IP为： 192.168.1.110
	 *  </p>
	 *  
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if ("127.0.0.1".equals(ip)) {
				/** 根据网卡取本机配置的IP */
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
					ip = inet.getHostAddress();
				} catch (UnknownHostException e) {
					logger.error("IpHelper error." + e.toString());
				}
			}
		}
		/**
		 * 对于通过多个代理的情况， 第一个IP为客户端真实IP,多个IP按照','分割 "***.***.***.***".length() =
		 * 15
		 */
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}
	
	/**
	 * 获取IP地理位置
	 * @param ip
	 * @return
	 */
	public static IpCity getIpCity(String ip) {
		if(StringUtils.isNotBlank(ip)) {
			String url = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip ;
			String asString = HttpClient.get(url).execute().asString();
			JSONObject data = JSON.parseObject(asString);
			Integer code = Integer.parseInt(data.get("code").toString());
			if(code == 0) {
				return JSON.parseObject(data.get("data").toString(), IpCity.class) ;
			}
		}
		return null ;
	}
	
	public static IpCity getIpCity(HttpServletRequest request) {
		return getIpCity(getIpAddr(request)) ;
	}
	
	public static void main(String[] args) {
		IpCity ipAddr = getIpCity("219.136.131.157");
		System.out.println(ipAddr);
	}
}

class IpCity {
	private String region ;
	private String area_id ;
	private String country_id ;
	private String isp ;
	private String region_id ;
	private String ip ;
	private String country ;
	private String city ;
	private String isp_id ;
	private String city_id ;
	private String area ;
	private String county ;
	public String getRegion() {
		return region;
	}
	public void setRegion(String region) {
		this.region = region;
	}
	public String getArea_id() {
		return area_id;
	}
	public void setArea_id(String area_id) {
		this.area_id = area_id;
	}
	public String getCountry_id() {
		return country_id;
	}
	public void setCountry_id(String country_id) {
		this.country_id = country_id;
	}
	public String getIsp() {
		return isp;
	}
	public void setIsp(String isp) {
		this.isp = isp;
	}
	public String getRegion_id() {
		return region_id;
	}
	public void setRegion_id(String region_id) {
		this.region_id = region_id;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getIsp_id() {
		return isp_id;
	}
	public void setIsp_id(String isp_id) {
		this.isp_id = isp_id;
	}
	public String getCity_id() {
		return city_id;
	}
	public void setCity_id(String city_id) {
		this.city_id = city_id;
	}
	public String getArea() {
		return area;
	}
	public void setArea(String area) {
		this.area = area;
	}
	public String getCounty() {
		return county;
	}
	public void setCounty(String county) {
		this.county = county;
	}
	@Override
	public String toString() {
		return "IpCity [region=" + region + ", area_id=" + area_id + ", country_id=" + country_id + ", isp=" + isp + ", region_id=" + region_id + ", ip=" + ip + ", country=" + country + ", city=" + city + ", isp_id=" + isp_id + ", city_id=" + city_id + ", area=" + area + ", county=" + county + "]";
	}
	
}
